<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>新增食堂</title>
    <link rel="stylesheet" href="plugins/layui/css/layui.css" media="all" />
    <link rel="stylesheet" href="css/comments.css" media="all">
    <style>
        .maincontainer .layui-form-label{
            width: 140px;
        }
        .maincontainer .layui-input-block{
            margin-left: 170px;
        }
		#tableForm{
			display: none;
            padding: 10px 20px;
		}
		#tableForm .layui-form-label{
            width: 90px;
        }
    </style>
</head>
<body>
    <div class="maincontainer">
        <blockquote class="layui-elem-quote">
            新增食堂
            <button type="button" class="layui-btn layui-btn-sm" style="float: right;margin-top: -4px;" onclick="window.history.back();">返回</button>
        </blockquote>
        <form class="layui-form" action="" lay-filter="example">
            <div class="layui-form-item">
                <label class="layui-form-label"><span class="redtext marginRight">*</span>账号：</label>
                <div class="layui-input-inline">
                  <input type="text" name="account" autocomplete="off" placeholder="请输入账号" class="layui-input" maxlength="20" readonly onfocus="this.removeAttribute('readonly');" onblur="this.setAttribute('readonly',true);">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label"><span class="redtext marginRight">*</span>密码：</label>
                <div class="layui-input-inline">
                    <input type="password" name="password" placeholder="请输入密码" autocomplete="off" class="layui-input" maxlength="20">
                </div>
                <div class="layui-form-mid layui-word-aux">注：6到20位字母或数字</div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label"><span class="redtext marginRight">*</span>确认密码：</label>
                <div class="layui-input-inline">
                    <input type="password" name="password1" placeholder="请输入确认密码" autocomplete="off" class="layui-input" maxlength="20">
                </div>
            </div>
			<div class="layui-form-item">
			    <label class="layui-form-label"><span class="redtext marginRight">*</span>食堂名称：</label>
			    <div class="layui-input-inline">
			      <input type="text" name="canteenName" autocomplete="off" placeholder="请输入食堂名称" class="layui-input" maxlength="50">
			    </div>
			</div>
			<div class="layui-form-item">
			    <label class="layui-form-label"><span class="redtext marginRight">*</span>食堂联系人：</label>
			    <div class="layui-input-inline">
			      <input type="text" name="contactPerson" autocomplete="off" placeholder="请输入食堂联系人" class="layui-input" maxlength="20">
			    </div>
			</div>
			<div class="layui-form-item">
			    <label class="layui-form-label"><span class="redtext marginRight">*</span>联系人电话：</label>
			    <div class="layui-input-inline">
			      <input type="text" name="contactTelephone" autocomplete="off" placeholder="请输入联系人电话" class="layui-input" maxlength="11">
			    </div>
			</div>
            <div class="layui-form-item">
                <label class="layui-form-label"><span class="redtext marginRight">*</span>状态：</label>
                <div class="layui-input-block">
                    <input type="radio" name="openStatus" value="1" title="启用" checked="" disabled>
                    <input type="radio" name="openStatus" value="0" title="禁用" disabled>
                </div>
            </div>
			<div class="layui-form-item">
			    <label class="layui-form-label"><span class="redtext marginRight">*</span>服务区域：</label>
			    <div class="layui-input-inline">
			        <select name="f" lay-filter="f"></select>
			    </div>
			    <div class="layui-input-inline">
			        <select name="s" lay-filter="s"></select>
			    </div>
			    <div class="layui-input-inline">
			        <select name="t" lay-filter="t"></select>
			    </div>
			</div>
			<div class="layui-form-item">
			    <label class="layui-form-label"></label>
			    <div class="layui-form-mid layui-word-aux remarks"></div>
			</div>
			<div class="layui-form-item">
			    <label class="layui-form-label"><span class="redtext marginRight">*</span>收货地址：</label>
			    <div class="layui-input-inline" style="min-width: 50%;">
			      	<textarea type="text" name="receiveAddress" autocomplete="off" placeholder="请输入收货地址" class="layui-textarea"></textarea>
			    </div>
			</div>
            <div class="layui-form-item">
                <label class="layui-form-label"><span class="redtext marginRight">*</span>是否允许代下单：</label>
                <div class="layui-input-block">
                    <input type="radio" name="replaceOrderStatus" value="1" title="是" checked="" lay-filter="replaceOrderStatus">
                    <input type="radio" name="replaceOrderStatus" value="0" title="否" lay-filter="replaceOrderStatus">
                </div>
            </div>
            <div class="layui-form-item replaceOrderSupplier">
                <label class="layui-form-label">指定代下单供应商：</label>
                <div class="layui-input-inline">
                    <button type="button" class="layui-btn selectProduct">选择</button>
                </div>
            </div>
            <div class="layui-form-item replaceOrderSupplier">
                <label class="layui-form-label"></label>
                <div class="layui-input-block">
                    <table class="layui-hide" id="goodsTable" lay-filter="goodsTable"></table>
                </div>
            </div>
            <div class="layui-form-item">
              <div class="layui-input-block">
                <button type="button" class="layui-btn" lay-submit="" lay-filter="demo1">确认</button>
                <button type="button" class="layui-btn layui-btn-primary" onclick="window.history.back()">取消</button>
              </div>
            </div>
        </form>
    </div>
    <div id="tableForm">
        <form id="tablequeryForm" class="layui-form" action=""></form>
            <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label">供应商名称：</label>
                    <div class="layui-input-inline">
                        <input type="text" name="supplierName" autocomplete="off" placeholder="供应商名称" class="layui-input" maxlength="20">
                    </div>
                </div>
                <div class="layui-inline">
                    <label class="layui-form-label">账号：</label>
                    <div class="layui-input-inline">
                        <input type="text" name="supplierAccount" autocomplete="off" id="tree" lay-filter="tree" class="layui-input">
                    </div>
                </div>
                <div class="layui-inline">
                    <button type="button" class="layui-btn searchGoods">查询</button>
                </div>
            </div>
        </form>
        <table class="layui-hide" id="selectTable" lay-filter="selectTable"></table>
    </div>
<script type="text/javascript" src="plugins/layui/layui.js"></script>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script>

    layui.config({
        base: 'plugins/layui/modules/',
    }).use(['http', 'form', 'table'], function() {
        var http = layui.http,
			form = layui.form,
			table = layui.table;

        // 服务区域
        var areaList,fList,sList
        http.get('food/manager/region/listAllRegion',{},function(res){
            if(res.code == 200){
                areaList = res.data
                var html = '<option value=""></option>';
        		for (var i = 0; i < areaList.length; i++) {
        			html += '<option value="' + areaList[i].id + '">' + areaList[i].regionName + '</option>'
        		}
        		$('select[name=f]').html(html);
        		form.render('select');
            }else{
                layer.msg(res.msg)
            }
        })
		//监听
		form.on('select(f)', function(data){
		    for (var i = 0; i < areaList.length; i++) {
		        if(areaList[i].id == data.value){
		            fList = areaList[i].children
		            var html = '<option value=""></option>';
		            if(fList){
		                for (var i = 0; i < fList.length; i++) {
		                    html += '<option value="' + fList[i].id + '">' + fList[i].regionName + '</option>'
		                }
		            }
		            $('select[name=s]').html(html);
		            $('select[name=t]').html('<option value=""></option>')
		            form.render('select');
		            break
		        }
		    }
		})
		form.on('select(s)', function(data){
		    for (var i = 0; i < fList.length; i++) {
		        if(fList[i].id == data.value){
		            sList = fList[i].children
		            var html = '<option value=""></option>';
		            if(sList){
		                for (var i = 0; i < sList.length; i++) {
		                    html += '<option value="' + sList[i].id + '">' + sList[i].regionName + '</option>'
		                }
		            }
		            $('select[name=t]').html(html);
		            form.render('select');
		            break
		        }
		    }
		})
		form.on('select(t)', function(data){
			replaceOrderSupplierIdSet = [],replaceOrderSupplierIdSetList = [];
			goodsFun() // 回显已选择的供应商列表
		    for (var i = 0; i < sList.length; i++) {
		        if(sList[i].id == data.value){
		            $('.remarks').html('注：该区域包括（'+sList[i].remarks+'）')
		            break
		        }
		    }
		})

		// 是否允许代下单
		form.on('radio(replaceOrderStatus)', function (data) {
			if(data.value == 0){ // 否
				$('.replaceOrderSupplier').hide()
			}else if(data.value == 1){ // 是
				$('.replaceOrderSupplier').show()
			}
		})
		
		var replaceOrderSupplierIdSet = [],
		replaceOrderSupplierIdSetList = [];
        // 选择供应商
        $(document).on('click','.selectProduct',function(){
			if(!$('select[name=t]').val()){
				layer.msg('请选择服务区域')
				return
			}
            tableFun()
            http.myOpen({
                title:'选择供应商',
                content: $('#tableForm'),
                area:['800px','720px'],
                btn:['确定','取消'],
                btn1:function(index, layero){
					if (replaceOrderSupplierIdSet.length == 0) {
						layer.msg("请勾选需要的供应商");
						return;
					}
					layer.close(index)
					goodsFun()
                }
            })
        })
		// 可选择的供应商列表
		var selectTable = '', table_data = []
        function tableFun(){
			// 查询跟食堂区域匹配的供应商
            selectTable = http.table({
                elem: '#selectTable',
                url: 'food/manager/supplier/listCanteenMatchSupplier',
                method: 'get',
                id: 'selectTable',
                height: 300,
                where: {
                    regionId: $('select[name=t]').val()
                },
                done: function(res, curr, count){
                    var data = res.data;
                    table_data = data
                    //在缓存中找到id ,然后设置data表格中的选中状态
                    //循环所有数据，找出对应关系，设置checkbox选中状态
                    for(var i=0;i< res.data.length;i++){
                        for (var j = 0; j < replaceOrderSupplierIdSet.length; j++) {
                            //数据id和要勾选的id相同时checkbox选中
                            if(res.data[i].id == replaceOrderSupplierIdSet[j]) {
                                //这里才是真正的有效勾选
                                res.data[i]["LAY_CHECKED"]='true';
                                //找到对应数据改变勾选样式，呈现出选中效果
                                var index= res.data[i]['LAY_TABLE_INDEX'];
                                $('#tableForm .layui-table-fixed-l tr[data-index=' + index + '] input[type="checkbox"]').prop('checked', true);
                                $('#tableForm .layui-table-fixed-l tr[data-index=' + index + '] input[type="checkbox"]').next().addClass('layui-form-checked');
                            }
                        }
                    }
                    //设置全选checkbox的选中状态，只有改变LAY_CHECKED的值， table.checkStatus才能抓取到选中的状态
                    var checkStatus = table.checkStatus('selectTable');
                    if(checkStatus.isAll){
                        $('#tableForm .layui-table-header th[data-field="0"] input[type="checkbox"]').prop('checked', true);
                        $('#tableForm .layui-table-header th[data-field="0"] input[type="checkbox"]').next().addClass('layui-form-checked');
                    }
                },
                cols: [[
                    {type:'checkbox',fixed: true},
                    {field:'supplierName', title: '供应商名称', align : 'center'},
                    {field:'account', title: '账号', align : 'center'},
                ]]
            });
        }
        //复选框选中监听,将选中的id 设置到缓存数组,或者删除缓存数组
        table.on('checkbox(selectTable)', function (obj) {
			var checkStatus = table.checkStatus('selectTable'); //获取选中行状态
			var data = checkStatus.data; //获取选中行数据
			for(var n=0;n<replaceOrderSupplierIdSetList.length;n++){
				for(var m=0;m<table_data.length;m++){
					if(replaceOrderSupplierIdSetList[n].id == table_data[m].id){
						replaceOrderSupplierIdSetList.splice(n,1)
						n--
						break
					}
				}
			}
			var list
			if(replaceOrderSupplierIdSetList.length == 0){
				list = data
			}else{
				list = replaceOrderSupplierIdSetList.concat(data)
			}
			replaceOrderSupplierIdSetList = unique5(list)
			function unique5(arr){
				replaceOrderSupplierIdSet=[];
				var hashList=[]
				for (var i = 0; i < arr.length; i++) {
					if(replaceOrderSupplierIdSet.indexOf(arr[i].id)==-1){
						replaceOrderSupplierIdSet.push(arr[i].id);
						hashList.push(arr[i])
					}
				}
				return hashList;
			}
        });
        // 查询
        $(document).on('click','.searchGoods',function(){
            selectTable.reload({
				page:{curr:1},
				where: {
					supplierName: $('#tableForm input[name=supplierName]').val(),
					supplierAccount: $('#tableForm input[name=supplierAccount]').val()
                }
			})
        })

        // 回显已选择的供应商列表
        function goodsFun() {
            http.table1({
                elem: '#goodsTable',
                id: 'goodsTable',
                cols: [[
                    {title:'序号',type:'numbers'},
                    {field:'supplierName', title: '供应商名称', align : 'center'},
                    {field:'account', title: '账号', align : 'center'},
                    {field:'', title: '操作', align : 'center',fixed: 'right',width: 130,
                        templet: function (d) {
                            var html = '';
                            html += '<button type="button" class="layui-btn layui-btn-primary layui-btn-xs" lay-event="del" >删除</button>'
                            return html;
                        }
                    }
                ]],
                limit: replaceOrderSupplierIdSetList.length,
                data: replaceOrderSupplierIdSetList
            })
		}
        // table操作
        table.on('tool(goodsTable)', function(obj){
            if(obj.event=='del'){
                // 删除
                var index = $(obj.tr).eq(0).data('index')
                replaceOrderSupplierIdSetList.splice(index,1)
                replaceOrderSupplierIdSet.splice(index,1)
                goodsFun()
            }
        })
        
        //监听提交
        form.on('submit(demo1)', function(data){
            console.log(data.field)
            if($.trim(data.field.account) == "") {
                layer.msg('请输入账号')
                return
            }
            if($.trim(data.field.password) == "") {
                layer.msg('请输入密码')
                return
            }
            if(!/^[0-9a-zA-Z]{6,20}$/.test(data.field.password)){
                layer.msg('密码不规范')
                return
            }
			if(data.field.password != data.field.password1){
			    layer.msg('密码不一致')
			    return
			}
			if($.trim(data.field.canteenName) == "") {
			    layer.msg('请输入食堂名称')
			    return
			}
			if($.trim(data.field.contactPerson) == "") {
			    layer.msg('请输入食堂联系人')
			    return
			}
			if($.trim(data.field.contactTelephone) == "") {
			    layer.msg('请输入联系人电话')
			    return
			}
			if(!/^1[345789]\d{9}$/.test(data.field.contactTelephone)){
			    layer.msg('手机号不规范')
			    return
			}
			if($.trim(data.field.f) == ""||$.trim(data.field.s) == ""||$.trim(data.field.t) == "") {
			    layer.msg('请选择服务区域')
			    return
			}
			if($.trim(data.field.receiveAddress) == "") {
			    layer.msg('请输入收货地址')
			    return
			}
            
            http.postJSON('food/manager/canteen/add',JSON.stringify({
                account: $.trim(data.field.account),
                password: data.field.password,
                canteenName: data.field.canteenName,
                contactPerson: data.field.contactPerson,
                contactTelephone: data.field.contactTelephone,
                // regionId:data.field.t,
                regionIdSet: [data.field.t],
				openStatus:data.field.openStatus,
				receiveAddress:data.field.receiveAddress,
				replaceOrderStatus: data.field.replaceOrderStatus, // 是否允许代下单 0否1是
				replaceOrderSupplierIdSet: replaceOrderSupplierIdSet // 代下单供应商集合
            }),function(res){
                if(res.code == 200){
                    layer.msg('操作成功')
                    setTimeout(function(){
                        window.history.back()
                    },500)
                }else{
                    layer.msg(res.msg)
                }
            })
        });
		
		// 失焦验证密码
		$("input[name=password]").blur(function(e){
			let password1 = $('input[name=password1]').val();
			http.verifPwd($(this).val(),password1,1);
		}) 
		$("input[name=password1]").blur(function(e){
			let password = $('input[name=password]').val();
			http.verifPwd(password,$(this).val(),2);
		})
    })
</script>
</body>